package cn.kwq.project_manger.service.impl;

import cn.kwq.project_manger.pojo.QResume;
import cn.kwq.project_manger.pojo.Resume;
import cn.kwq.project_manger.pojo.dto.AddResumeDto;
import cn.kwq.project_manger.pojo.dto.ResResumeDto;
import cn.kwq.project_manger.pojo.dto.ResumeUserDto;
import cn.kwq.project_manger.repostitory.ResumeRepository;
import cn.kwq.project_manger.service.ResumeService;
import cn.kwq.project_manger.service.UserService;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class ResumeServiceImpl implements ResumeService {
    @Autowired
    UserService userService;
    @Autowired
    ResumeRepository resumeRepository;
    @Autowired
    JPAQueryFactory jpaQueryFactory;


    @Override
    @Transactional
    public ResResumeDto addResume(AddResumeDto dto, Long userId) {
        ResumeUserDto msgForResume = userService.getMsgForResume(userId);
        QResume resume=QResume.resume;
        //通过userid查找出原来的简历id
        Long resumeId = jpaQueryFactory.select(resume.resumeId)
                .from(resume)
                .where(resume.userId.eq(userId))
                .fetchOne();
        Resume addResume = dto.getResume(resumeId, userId);
        addResume.setResumeName(msgForResume.getUserName()+"的简历");
        Resume save = resumeRepository.save(addResume);
        log.info("["+msgForResume.getUserName()+"]简历信息保存成功");
        return ResResumeDto
                .builder()
                .resumeMsg(save)
                .wyuMsg(msgForResume)
                .build();
    }

    @Override
    public ResResumeDto getResume(Long userId) {

        ResumeUserDto msgForResume = userService.getMsgForResume(userId);
        QResume resume=QResume.resume;
        //通过userid查找出原来的简历id
        Resume getResume = jpaQueryFactory
                .selectFrom(resume)
                .where(resume.userId.eq(userId))
                .fetchOne();
        //如果数据库查出数据直接返回
        if (getResume!=null){
            return ResResumeDto
                    .builder()
                    .resumeMsg(getResume)
                    .wyuMsg(msgForResume)
                    .build();
        }else {
            //没有数据只返回教务系统相关信息，懒创建
            return ResResumeDto
                    .builder()
                    .wyuMsg(msgForResume)
                    .resumeMsg(new Resume())
                    .build();
        }


    }




}
